<!DOCTYPE html>

<html lang="en">
<head>
<title>Secure Mobile Device Management - PoC</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<!-- Styles, taken from Bootstrap Sign-in Form Example.-->
<style type="text/css">
body {
	padding-top: 40px;
	padding-bottom: 40px;
	background-color: #f5f5f5;
}

.regDevicesSection {
	margin-top: 30px;
}

.devicenameCol {
	max-width: 150px;
}

.deviceIdCol {
	max-width: 300px; //
	overflow: hidden; // text-overflow : ellipsis; // white-space : nowrap;
	width : 300px;
	word-wrap: break-word;
	text-overflow: ellipsis; //
	white-space: nowrap;
	width: 300px;
}

.form-policy {
	max-width: 230px;
	padding: 29px 29px 29px;
	margin: 50px auto 20px;
	background-color: #fff;
	border: 1px solid #e5e5e5;
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
	border-radius: 5px;
	-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .05);
	-moz-box-shadow: 0 1px 2px rgba(0, 0, 0, .05);
	box-shadow: 0 1px 2px rgba(0, 0, 0, .05);
}

.form-policy input[type="text"] {
	font-size: 16px;
	height: auto;
	margin-bottom: 15px;
	padding: 7px 9px;
}

.alertStyle {
	max-width: 300px;
	margin: 5px auto 20px;
}

.btn-lri-right {
	float: right; //
	margin-left: 15px; //
	padding-left: 15px;
}
</style>

<!-- 
	JavaScript for the GCM registered devices lookup and sending the mdm messages. 
<script type="text/javascript" src="policyupdate.js" />
 -->

<script type="text/javascript">

API_URL = 'https://' + window.location.host + '/_ah/api';

if (window.location.hostname == 'localhost'
    || window.location.hostname == '127.0.0.1'
    || ((window.location.port != "") && (window.location.port > 999))) {
    // We're probably running against the DevAppServer
    API_URL = 'http://' + window.location.host + '/_ah/api';
}

  function showSuccess() { 
    $("#alertArea").hide();
    $("#successArea").show();
    $("#successArea").fadeOut(1000);
  }
  
  function showError(errorHtml) {
    $("#alertArea").removeClass('alert-error alert-info alert-success').addClass('alert-error');
    $("#alertContentArea").html(errorHtml);
    $("#alertArea").show();
  }
    
  function showInfo(infoHtml) {
    $("#alertArea").removeClass('alert-error alert-info alert-success').addClass('alert-info');
    $("#alertContentArea").html(infoHtml);
    $("#alertArea").show();
  }
  

  // This method loads the deviceinfoendpoint and messageEndpoint libraries
  function loadGapi() {
    gapi.client.load('deviceinfoendpoint', 'v1', function() {
      updateRegisteredDeviceTable();
    });
    
    gapi.client.load('messageEndpoint', 'v1', function() {});
  }

  // Specialized function for checking error responses; it's needed to work around bugs in the
  // current version of the DevAppServer
  function checkErrorResponse(result, rawResult) {      
    // Generally, !result should never occur. It's a bug with the DevAppServer. It will be fixed
    // in a forthcoming version of App Engine.    
    if (!result) {           
      try {
        // This is some special exception-handling code to deal with the DevAppServer not 
        // handling empty (void responses) from an endpoint method in App Engine 1.7.5.
        result = JSON.parse(rawResult);
      } catch (err) {
      // This is a spurious error. Return true.
      if (rawResult.indexOf("Error 400 Failed to parse JSON request: Unexpected character") != -1) {
          return {isError: false};
      } else {
        if (rawResult == "") {
          // Empty result; perhaps we're disconnected?
          return {isError: true, errorMessage: "No response from server! Is it up and running?" };

        } else {
          // Unknown error; this shouldn't really happen
          var safeErrorHtml = $('<div/>').text(rawResult).html();
          return {isError: true, errorMessage: safeErrorHtml};
        }         
      }
      }   
    }   
      
    if (result.error) {
      // This is really what should happen; if there's an error, a result.error object will
      // exist
          var safeErrorHtml = $('<div/>').text(result.error.message).html();
      return {isError: true, errorMessage: safeErrorHtml};
    } else if (result[0] && result[0].error) {
      // This is yet another hack; the DevAppServer incorrectly returns an array of error
      // responses in the case where the endpoint method throws an app-level exception.
      // Again, this will be fixed in a forthcoming version of App Engine.
          var safeErrorHtml = $('<div/>').text(result[0].error.message).html();
      return {isError: true, errorMessage: safeErrorHtml};
    }
    
    return {isError: false};
  }
  
  function generateRegDeviceTable(deviceInfoItems) {
    items = deviceInfoItems.items;
  
    if (!items || items.length == 0) {
      var htmlString = "<thead>"
          + "<tr>"
          + "<th>There are no registered devices</th>"
          + "</tr>" + "</thead>"
          + "<tbody></tbody>";
      $("#regDevicesTable").html(htmlString);
    } else {
      var htmlString = "<thead>" + "<tr>"
          + "<th style='min-width:150px'>Device Name</th>"
          + "<th>Registration Id</th>"
          + "<th>Timestamp</th>" 
          + "<th>CameraDisabled</th>" 
          + "<th>PasswordForced</th>" 
          + "<th>Position</th>" 
          + "</tr>" + "</thead>"          
          + "<tbody>";
          
      for (var i = 0; i < items.length; i++) {
        item = items[i];
        htmlString += "<tr>";
        if (item.deviceInformation) {
          htmlString += "<td class='devicenameCol'>" + item.deviceInformation
              + "</td>";
        } else {
          htmlString += "<td class='devicenameCol'>" + "(unknown)"
              + "</td>";
        }

        if (item.deviceRegistrationID) {
          htmlString += "<td class='deviceIdCol'>" + item.deviceRegistrationID + "</td>";
        } else {
          htmlString += "<td class='deviceIdCol'>" + "(unknown)"
          + "</td>";        
        }
        
        
        if (item.timestamp) {
          var timestampNumberic = new Number(item.timestamp);
          var date = new Date(timestampNumberic);

          
            htmlString += "<td>" + date.toString() + "</td>";
          } else {
            htmlString += "<td>" + "(unknown)"
            + "</td>";        
          }
          
          // LRI added for camera enabled
      	//if (item.cameraEnabled) {
      		htmlString += "<td>" + item.cameraEnabled + "</td>";
      		//} else {
      		//htmlString += "<td>" + "false" + "</td>";
      	//}
      	
      	//if(item.passwordForced) {
      		htmlString += "<td>" + item.passwordForced + "</td>";
      		//} else {
      		//htmlString += "<td>" + "(unknown)" + "</td>";
      	//}
      	
      	if 	(item.position) {
      		htmlString += "<td>" + item.position + "</td>";
      		} else {
      		htmlString += "<td>" + "(unknown)" + "</td>";
      	}
        
        htmlString += "</tr>";
      }

      htmlString += "</tbody>";
      $("#regDevicesTable").html(htmlString);
    }
  }
  
  function updateRegisteredDeviceTable() {
    gapi.client.deviceinfoendpoint
        .listDeviceInfo({})
        .execute(
            function(deviceInfoItems, deviceInfoItemsRaw) {
              errorResult = checkErrorResponse(deviceInfoItems, deviceInfoItemsRaw);
              if (errorResult.isError) {
                showError("There was a problem contacting the server when attempting to list the registered devices. " 
                    + "Please refresh the page and try again in a short while. Here's the error information:<br/> "
                    + errorResult.errorMessage);
              } else {
                generateRegDeviceTable(deviceInfoItems);              
              }
            });
            
		// XXX might not be a good idea to do this every two seconds
      //  setTimeout("updateRegisteredDeviceTable()", 2000);
        
  }
  
  function handleMessageResponse(data, dataRaw) {
    errorResult = checkErrorResponse(data, dataRaw);    
    if (!errorResult.isError) { 
        showSuccess();        
    } else {
    showError("There was a problem when attempting to send the message using the server at " 
        + API_URL + ". " + " Is your API Key in MessageEndpoint.java "  
        + "(in your App Engine project) set correctly? Here's the error information:<br/>"
            + errorResult.errorMessage);
    }
  }
  
  function sendMessage() {
    var message = $("#inputMessage").val();

	var e = document.getElementById("checkboxCamera");
	var selectCamera = e.options[e.selectedIndex].text;
	
	var f = document.getElementById("checkboxPassword");
	var selectPassword = f.options[f.selectedIndex].text;

	message = "SMDM camera " + selectCamera + " password " + selectPassword;
	//showInfo(message); 
	//console.log(message);
    if (message == "") {
      showInfo("Message must not be empty!");
      } else {
        gapi.client.messageEndpoint
        .sendMessage({"message": message})
        .execute(handleMessageResponse);
      }
  }

  
</script>
</head>

<body>
	<div class="container">
		<h1>Secure Mobile Device Management - PoC</h1>
		<p style="">This proof of concept application lists all of your
			registered Android devices.</p>
		<p>Use the form below to send a policy update (Cloud Endpoints) to
			your Application Engine Server, which will then send a message (Cloud
			Messaging) to all of your registered devices. The Android Application
			itself will then enforce the new policy.</p>


		<div class="form-policy">
			<label><h3>Policy Definition:</h3></label>
			<!-- <input class="input-block-level" type="text" id="inputMessage"
				placeholder="Message"> -->
			<label>Camera:</label> <select name="checkbox" id="checkboxCamera">
				<option value="1">enable</option>
				<option value="2">disable</option>
			</select> <label>Password enforced:</label> <select name="checkbox"
				id="checkboxPassword">
				<option value="1">no</option>
				<option value="2">enforce</option>
			</select>
			<!-- <input type="checkbox" name="zutat" value="salami" id="check1" class="btn"> HUHU</input><label for="check1">Salami</label> -->

			<button id="refreshButton" class="btn btn-large btn-primary ">Refresh</button>
			<button id="sendButton"
				class="btn btn-large btn-primary btn-lri-right">Send</button>
		</div>


		<div id="alertArea" class="alert alertStyle">
			<button type="button" class="close">&times;</button>
			<div id="alertContentArea"></div>
		</div>

		<div id="successArea" class="alert alertStyle alert-success fade in">
			Policy update sent!</div>

		<div class="regDevicesSection">
			<h3>Registered Devices:</h3>
			<table class="table table-striped" id="regDevicesTable">
				<thead>
					<tr>
						<th>Searching for registered devices...</th>
					</tr>
				</thead>
			</table>
		</div>

	</div>
	<div class='container navbar navbar-fixed-bottom'>
		<p class='text-error'>
			<a href="/hello" />Hello World Sample</a> <a href="/login" />Login
			Sample</a> <a href="/open" />Open ID Sample</a>
		</p>
	</div>

	<!-- JavaScript -->
	<script src="https://apis.google.com/js/client.js?onload=loadGapi">
  {
    "client": {},
      "googleapis.config": {
        root: API_URL
      }
  }
  </script>
	<script src="js/jquery-1.9.0.min.js"></script>
	<script src="js/bootstrap.min.js"></script>

	<script type="text/javascript">
    $("#sendButton").click(sendMessage);
    $("#refreshButton").click(updateRegisteredDeviceTable);
    $("#alertArea").hide();
    $("#successArea").hide();
    $('.alert .close').on('click', function() {
      $(this).parent().hide();
    })
  </script>
</body>
</html>